
<div class="layui-card layadmin-header">
  <div class="layui-breadcrumb" lay-filter="breadcrumb">
    <a lay-href="">主页</a>
    <a><cite>用户管理</cite></a>
  </div>
</div>

<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-tab layui-tab-brief">
      <ul class="layui-tab-title">
        <li class="layui-this">用户列表</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
          <div class="layui-row">
            <div class="layui-form" style="float:right;">
              <div class="layui-form-item" style="margin:0;">
                <div class="layui-input-inline">
                  <input type="text" name="userId" id="userId" autocomplete="off" placeholder="用户ID" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <input type="text" name="userName" id="userName" autocomplete="off" placeholder="用户名" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <select name="type" id="state" lay-search="">
                    <option value="-99">状态</option>
                    <option value="1">启用</option>
                    <option value="0">停止</option>
                  </select>
                </div>
                <button id="search" class="layui-btn" data-type="reload">
                  <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                </button>
              </div>
            </div>
          </div>
          <div class="layui-card-body">
            <div style="padding-bottom: 10px;">
              <button class="layui-btn layuiadmin-btn-list" data-type="add">添加</button>
              <button class="layui-btn" data-type="del">删除</button>
            </div>
          </div>
          <table id="Pay_Mgr_User_dataAll" lay-filter="Pay_Mgr_User_dataAll"></table>
        </div>

      </div>
    </div>
  </div>
</div>

<script type="text/html" id="payBar">
  <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="detail">查看</a>
  <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="userRole">分配角色</a>
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script src="layui/layui-xtree/layui-xtree.js"></script>
<script>
layui.use(['admin', 'table', 'util','form'], function(){
  var $ = layui.$
  ,admin = layui.admin
  ,table = layui.table
  ,element = layui.element,
      view =layui.view
      ,layer =layui.layer
  ,form = layui.form;

  element.render('breadcrumb', 'breadcrumb');

  var tplStatus = function(d) {
      if (d.state == 1) {
          return "<span class='layui-btn layui-btn-xs'>启用</span>";
      }
      return "<span class='layui-btn layui-btn-xs layui-btn-disabled'>停止</span>";
  }
  //用户列表
  table.render({
    elem: '#Pay_Mgr_User_dataAll'
    ,url: layui.setter.baseUrl + '/sys/user/list' //用户列表接口
    ,where: {
      access_token: layui.data(layui.setter.tableName).access_token
    }
    ,id: 'tableReload'
    ,page: true
    ,cols: [[
      {type: 'checkbox', fixed: 'left'}
      ,{field: 'userId', title: '用户ID'}
      ,{field: 'userName', title: '用户名'}
      ,{field: 'nickName', title: '用户昵称'}
      ,{field: 'state', title: '状态', templet: tplStatus}
      ,{field: 'createTime', title: '创建时间', templet: '<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss") }}</div>'}
      ,{field: 'edit', width:260, title: '操作', toolbar: '#payBar' }
    ]]
    ,skin: 'line'
  });

  //监听工具条
  table.on('tool(Pay_Mgr_User_dataAll)', function(obj){
    var data = obj.data;
    if(obj.event === 'detail'){

        var userId = data.userId;
        admin.req({
            type: 'get',
            url: layui.setter.baseUrl + '/sys/user/get',
            data: {
                userId : userId
            },
            error: function(err){
                layer.alert(JSON.stringify(err.field), {
                    title: '错误提示'
                })
            },
            success: function(res){
                if(res.code == 0){

                    data=res.data;

                    admin.popup({
                        title: '用户详情'
                        , area: ['400px', '435px']
                        , id: 'LAY-popup-content-detail'
                        , success: function (layero, index) {
                            view(this.id).render('sys/user/user_view').done(function () {
                                form.render(null, 'layuiadmin-app-form-list');

                                var body =layer.getChildFrame('body',index);
                                body.find('#email').val(data.email);
                                form.val("layuiadmin-app-form-list",{

                                      "userId":data.userId,
                                    "userName":data.userName,
                                    "nickName":data.nickName,
                                    "email":data.email,
                                    "mobile":data.mobile,
                                    "state":data.state==1?"启用":"停止"

                                })
                            });
                        }
                    });


                }
            }
        })


    } else if(obj.event === 'del'){
        layer.confirm('确认删除么', function(index){
            admin.req({
                url:layui.setter.baseUrl + '/sys/user/delete',
                data:{userIds: data.userId},
                success: function(){
                    layer.msg('删除成功', {
                        icon: 1
                    });
                    table.reload("tableReload");
                }
            });
        });

    } else if(obj.event === 'edit'){

        var userId=data.userId

        admin.req({
            type: 'get',
            url: layui.setter.baseUrl + '/sys/user/get',
            data: {
                userId : userId
            },
            error: function(err){
                layer.alert(JSON.stringify(err.field), {
                    title: '错误提示'
                })
            },
            success: function(res){
                if(res.code == 0){

                    admin.popup({
                        title: '修改用户'
                        , area: ['512px', '600px']
                        , id: 'LAY-popup-content-edit'
                        , success: function (layero, index) {
                            view(this.id).render('sys/user/user_edit').done(function () {
                                form.render(null, 'layuiadmin-app-form-list');

                                // 自定义表单验证 pass
                                form.verify({
                                  pass: [
                                    /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/
                                    ,'不符合密码为8-16位的字母和数字组合'
                                  ]
                                })

                                var body =layer.getChildFrame('body',index);
                                body.find('#email').val(data.email);
                                form.val("layuiadmin-app-form-list", {

                                   "userId":data.userId,
                                    "userName": data.userName,
                                    "nickName":data.nickName,
                                    "email":data.email,
                                    "mobile":data.mobile,
                                })
                                if(res.data.state == 1) {
                                    $("input[name='state'][value='1']").attr("checked",true);
                                }else {
                                    $("input[name='state'][value='0']").attr("checked",true);
                                }
                                form.render();

                                form.on('submit(userEdit)', function(data) {
                                    //这里可以写ajax方法提交表单
                                    $.ajax({
                                        type: "POST",
                                        url: layui.setter.baseUrl + '/sys/user/update',
                                        data: "params=" + JSON.stringify(data.field),
                                        success: function(res){
                                            if(res.code == 0) {
                                                /*layer.alert(res.msg,{title: "保存成功"},function(index){
                                                    table.reload('tableReload');
                                                    layer.closeAll();
                                                })*/
                                                layer.msg('保存成功', {
                                                    offset: '15px'
                                                    ,icon: 1
                                                    ,time: 1000
                                                }, function(){
                                                    table.reload('tableReload');
                                                    layer.closeAll();
                                                });
                                            }else {
                                               /* layer.alert(res.msg, {
                                                    title: '保存失败'
                                                });*/
                                                layer.msg('保存失败', {
                                                    offset: '15px'
                                                    ,icon: 1
                                                    ,time: 1000
                                                });
                                            }
                                        }
                                    });
                                    return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                                });

                            });
                        }
                    });


                }
            }
        })


    } else if(obj.event === 'userRole') {

        var userId =data.userId;
        var userRoleTree;

        admin.req({
            type: 'get',
            url: layui.setter.baseUrl + '/sys/user/user_role_view',
            data: {
                userId : userId
            },
            error: function(err){
                layer.alert(JSON.stringify(err.field), {
                    title: '错误提示'
                })
            },
            success: function(res){
                if(res.code == 0){

                    admin.popup({
                        title: '分配角色'
                        , area: ['260px', '330px']
                        , id: 'LAY-popup-content-edit'
                        , success: function (layero, index) {
                            view(this.id).render('sys/user/user_role_save').done(function () {
                                form.render(null, 'layuiadmin-app-form-list');
                                userRoleTree = new layuiXtree({
                                    elem: 'userRoleTree'    //(必填) 放置xtree的容器，样式参照 .xtree_contianer
                                    , form: form        //(必填) layui 的 from
                                    , data: res.data    //(必填) json数据
                                });

                                form.render();

                                //监听提交
                                form.on('submit(userRoleSave)', function(data) {
                                    // 获取所有选中的
                                    var oCks = userRoleTree.GetAllCheckBox();
                                    var roleIds = "";
                                    for (var i = 0; i < oCks.length; i++) {
                                        if(oCks[i].checked) {
                                            roleIds = roleIds + "," + oCks[i].value;
                                        }
                                    }
                                    roleIds = roleIds.substring(1);
                                    console.log(roleIds);

                                    //这里可以写ajax方法提交表单
                                    $.ajax({
                                        type: "POST",
                                        url: layui.setter.baseUrl + '/sys/user/user_role_save',
                                        data: {
                                            userId: userId,
                                            roleIds: roleIds,
                                        },
                                        success: function(res){
                                            if(res.code == 0) {

                                                    table.reload('tableReload');
                                                    layer.close(index);

                                            }else {
                                                layer.alert(res.msg, {
                                                    title: '保存失败'
                                                });
                                            }
                                        }
                                    });
                                    return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                                });

                            });
                        }
                    });

                }
            }
        });

    }

  });


  // 搜索
  var $ = layui.$, active = {
    reload: function(){
      var userId = $('#userId').val();
      var userName = $("#userName").val();
      var state = $("#state").val();
      //执行重载
      table.reload('tableReload', {
        page: {
          curr: 1 //重新从第 1 页开始
        }
        ,where: {
          userId: userId,
          userName: userName,
          state : state
        }
      });
    }

      ,add: function (othis) {
          admin.popup({
              title: '新建用户'
              , area: ['512px', '515px']
              , id: 'LAY-popup-content-add'
              , success: function (layero, index) {
                  view(this.id).render('sys/user/user_add').done(function () {

                    // 自定义表单验证 pass
                    form.verify({
                      pass: [
                        /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/
                        ,'不符合密码为8-16位的字母和数字组合'
                      ]
                    })
                      form.render(null, 'layuiadmin-app-form-list');

                      //监听提交

                      form.on('submit(userAdd)', function(data) {
                          //这里可以写ajax方法提交表单
                          $.ajax({
                              type: "POST",
                              url: layui.setter.baseUrl + '/sys/user/add',
                              data: "params=" + JSON.stringify(data.field),
                              success: function(res){
                                  if(res.code == 0) {
                                          table.reload('tableReload');
                                          layer.close(index);
                                  }else {
                                      /*layer.alert(res.msg, {
                                          title: '保存失败'
                                      });*/
                                      layer.msg('保存失败', {
                                          offset: '15px'
                                          ,icon: 1
                                          ,time: 1000
                                      });
                                  }
                              }
                          });
                          return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                      });
                  });
              }
          });
      }

      ,del :function(othis){
          var checkStatus = table.checkStatus("tableReload")
              ,data = checkStatus.data; //获得选中的数据
          if(data.length === 0) return layer.msg('请选择数据');
          console.log(data);
          layer.confirm('确定删除选中的数据吗？', function(index){

              var userIds = "";
              $.each(data, function(i, n){
                  userIds = userIds + "," + n.userId;
              });

              if(userIds != "") {
                  userIds = userIds.substring(1);
                  admin.req({
                      url:layui.setter.baseUrl + '/sys/user/delete',
                      data: {
                          userIds: userIds
                      },
                      success: function(){
                          layer.msg('删除成功', {
                              icon: 1
                          });
                          table.reload("tableReload");
                      }
                  });
              }



          });
      }
  };
  $('#search').on('click', function() {
    var type = $(this).data('type');
    active[type] ? active[type].call(this) : '';
  });

  $('.layui-btn.layuiadmin-btn-list').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    $('.layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

  // 渲染表单
  form.render();
});
</script>